<?php

namespace Togetwzb\Yii2\Aliyun\Oss\filters;

use OSS\Core\OssException;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\validators\Validator;

/**
 * 文件迁移过滤器
 * ```
 * model::rule
 *
 *  ['file', FileExistValidator::class, 'filterParamsCallback' => function ($model, $attribute) {
 *      return new FilterParams(['']);
 * }],
 * ```
 */
class FileFilter extends Validator
{
    /**
     * @var callable  filterParamsCallback($model, $attribute):FilterParams
     */
    public $filterParamsCallback;


    public function init()
    {
        parent::init();

        if (!is_callable($this->filterParamsCallback)) {
            throw new InvalidConfigException('paramsCallback Not a callback function.');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function validateAttribute($model, $attribute)
    {
        /** @var \yii\base\Model $model */

        $fun = $this->filterParamsCallback;
        $filterParams = $fun($model, $attribute);

        if (!($filterParams instanceof FilterParams)) {
            throw new Exception('filterParams not instanceof FilterParams.');
        }

        try {
            $filterParams->ossClient->copyObject($filterParams->fromBucket, $filterParams->fromObject, $filterParams->toBucket, $filterParams->toObject, $filterParams->ossOption);
            $model->$attribute = $filterParams->toObject;
            $filterParams->ossClient->deleteObject($filterParams->fromBucket, $filterParams->fromObject, $filterParams->deleteOption);
        } catch (OssException $e) {
            throw new Exception($e->getMessage());
        }
    }

}